<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="proName">
        <el-input
          v-model="queryParams.proName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择项目状态" clearable style="width: 150px;">
          <el-option label="未启用" value="0" />
          <el-option label="已启用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['project:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目ID" align="center" prop="id" width="80" />
      <el-table-column label="项目名称" align="center" prop="proName" />
      <el-table-column label="项目描述" align="center" prop="proDesc" />
      <el-table-column label="项目状态" align="center" prop="status">
        <template #default="scope">
          <span v-if="scope.row.status === 0 || scope.row.status === '0'" class="el-tag el-tag--default">未启用</span>
          <span v-else-if="scope.row.status === 1 || scope.row.status === '1'" class="el-tag el-tag--success">已启用</span>
        </template>
      </el-table-column>
      <el-table-column label="机器限制" align="center" prop="machineRestricted">
        <template #default="scope">
          <span v-if="scope.row.machineRestricted === 0 || scope.row.machineRestricted === '0'" class="el-tag el-tag--default">否</span>
          <span v-else-if="scope.row.machineRestricted === 1 || scope.row.machineRestricted === '1'" class="el-tag el-tag--primary">是</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['project:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['project:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="projectRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="proName">
          <el-input v-model="form.proName" placeholder="请输入项目名称" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="项目描述" prop="proDesc">
          <el-input v-model="form.proDesc" type="textarea" placeholder="请输入项目描述" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="项目状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择项目状态" style="width: 100%;">
            <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="机器限制" prop="machineRestricted">
          <el-select v-model="form.machineRestricted" placeholder="请选择是否需要机器限制" style="width: 100%;">
            <el-option label="否" :value="0" />
            <el-option label="是" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject, exportProject } from '@/api/project';

export default {
  name: 'Project',
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 项目表格数据
      projectList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        proName: '',
        status: '',
        createTime: ''
      },
      // 表单参数
      form: {
        id: null,
        proName: '',
        proDesc: '',
        status: 1, // 默认设置为已启用状态(数字类型)
        machineRestricted: 0, // 默认不需要机器限制
        createBy: '',
        createTime: null,
        updateBy: '',
        updateTime: null,
        remark: ''
      },
      // 表单校验
      rules: {
        proName: [
          { required: true, message: '项目名称不能为空', trigger: 'blur' }
        ]
      },
      // 字典数据 - 系统正常/禁用状态
      sys_normal_disable: [
        { label: '未启用', value: '0' },
        { label: '已启用', value: '1' }
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询项目列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        proName: '',
        proDesc: '',
        status: 1, // 默认设置为已启用状态(数字类型)
        machineRestricted: 0, // 默认不需要机器限制
        createBy: '', // 由于this.$store不存在，暂时设为空字符串
        createTime: null,
        updateBy: '',
        updateTime: null,
        remark: ''
      };
      this.resetForm('projectRef');
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮
    resetQuery() {
      this.resetForm('queryRef');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 新增按钮
    handleAdd() {
      this.title = '新增项目';
      this.reset();
      // 先设置表单状态，再显示弹窗，确保正确的DOM更新时序
      this.$nextTick(() => {
        this.form.status = 1;
        this.open = true;
      });
    },
    // 修改按钮
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProject(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = '修改项目';
      });
    },
    // 提交按钮
    submitForm() {
      this.$refs['projectRef'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProject(this.form).then(response => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addProject(this.form).then(response => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 删除按钮
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除项目编号为"' + ids + '"的数据项？').then(function() {
        return delProject(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess('删除成功');
      }).catch(() => {
      });
    },
    // 导出按钮
    handleExport() {
      this.$confirm('是否确认导出所有项目数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return exportProject(this.queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(() => {
      });
    }
  }
};
</script>